<?php

 class Controller_Mobile_Fenxiao_Jieshao extends Stourweb_Controller
{

    public function before()
    {
        parent::before();
        Common::before_header();
    }
    public function action_joinus()
    {
        Model_Fenxiao::save_fxcode();
        $member_info = Model_Member_Login::check_login_info();
        $member_info = Model_Member::get_member_byid($member_info['mid']);
        $result = DB::select('id','status')->from('fenxiao')->where('memberid','=',$member_info['mid'])->execute()->current();
        if($result['status'] == '1')
        {
            Request::current()->redirect('/fenxiao');
        }
        $this->assign('member',$member_info);
        $guide=Model_Fenxiao_Config::get_val('cfg_fenxiao_guide');
        $this->assign('guide',$guide);
        $this->display('../mobile/fenxiao/jieshao/joinus');
    }
     public function action_jieshao()
     {
         $content = Model_Fenxiao_Config::get_val('cfg_fenxiao_content');
         $this->assign('content',$content);
         $this->display('../mobile/fenxiao/jieshao/jieshao');
     }

     public function action_share()
     {
         $member_info = Model_Member_Login::check_login_info();
         $member_info = Model_Member::get_member_byid($member_info['mid']);
         $this->assign('member',$member_info);

         $isnew = $_GET['isnew'];
         $fenxiao_ways = Model_Fenxiao_Config::get_val('cfg_fenxiao_ways');
         $fenxiao_ways = explode(',',$fenxiao_ways);

         $fenxiao_pic_parts = Model_Fenxiao_Config::get_val('cfg_fenxiao_pic_parts');
         $fenxiao_pic_parts_arr = explode(',',$fenxiao_pic_parts);

         $fenxiao_pic_introduce = Model_Fenxiao_Config::get_val('cfg_fenxiao_pic_introduce');
         $fenxiao_pic_introduce_tpl1 = Model_Fenxiao_Config::get_val('cfg_fenxiao_pic_introduce_tpl1');

         $logo = $GLOBALS['cfg_m_logo'];
         $logo = substr($logo,strpos($logo,'/uploads'));

         $url=urldecode($_POST['url']);
         $url_main_path = str_replace('http://','',$url);
         $url_main_path = str_replace('https://','',$url_main_path);
         $url_main_path = str_replace(trim($GLOBALS['mobile_host'],'/\\').'/'.trim($GLOBALS['cfg_phone_cmspath'],'/').'/','',$url_main_path);
         $match=array();
         preg_match("/(([a-z0-9]*)[\\\\\/]){0,1}([a-z]+)[\\\\\/]{1}show_([0-9]+)/i",$url_main_path,$match);

         $dest_pinyin = $match[2];
         $webid = 0;
         if(!empty($dest_pinyin))
         {
             $webid = DB::select('id')->from('destinations')->where('pinyin','=',$dest_pinyin)->execute()->get('id');
             $webid = empty($webid)?0:$webid;
         }

         //判断是否为子站
         if($webid==0)
         {
             $url_info = parse_url($url);
             $url_host = $url_info['host'];
             $webid = DB::select('id')->from('destinations')->where('weburl','like','%'.$url_host.'%')->and_where('iswebsite','=',1)->execute()->get('id');
             $webid = empty($webid)?0:$webid;
         }


         $module_name = $match[3];
         $aid = $match[4];


         $model = DB::select()->from('model')->where('correct','=',$module_name)->or_where('pinyin','=',$module_name)->execute()->current();
         $product_piclist = array();
         if(!empty($model))
         {
             $product = DB::select()->from($model['maintable'])->where('aid','=',$aid)->and_where('webid','=',$webid)->execute()->current();

             $litpic_org = $product['litpic'];


             $litpic = Model_Fenxiao::dowload_picture($product['litpic']);
             if(!empty($litpic))
             {
                 //DB::update($model['maintable'])->set(array('litpic'=>$litpic))->where('aid','=',$aid)->and_where('webid','=',$webid)->execute();
                 $product['litpic'] = $litpic;
             }


             $piclist_arr = explode(',',$product['piclist']);
             foreach($piclist_arr as $pic)
             {
                 $pic_info = explode('||',$pic);
                 $sub_pic = $pic_info[0];
                 if($sub_pic==$litpic_org)
                 {
                     continue;
                 }

                 if(strpos($pic_info[0],'http://')!==false || strpos($pic_info[0],'https://')!==false)
                 {

                     $down_pic = Model_Fenxiao::dowload_picture($pic_info[0]);
                     //  if(!empty($down_pic))
                     //{
                     $sub_pic = $down_pic;
                     // }
                 }
                 if(!empty($sub_pic) && count($product_piclist)<2)
                 {
                     $product_piclist[] = $sub_pic;
                 }
             }




             $price = Model_Fenxiao::get_price($model['id'],$product['id']);
             $price = empty($price)?'':$price;

             $replace_params = array('SELLPOINT'=>$product['sellpoint'],
                 'TITLE'=>$product['title'],
                 'PRICE'=>$price,
                 'LINK'=>$url,
             );

             $weixin_title = Model_Fenxiao_Config::get_val('cfg_fenxiao_weixin_title');
             $weibo_content = Model_Fenxiao_Config::get_val('cfg_fenxiao_weibo_content');
             $copylink_content = Model_Fenxiao_Config::get_val('cfg_weixin_copylink_content');

             foreach($replace_params as $key=>$val)
             {
                 $weixin_title = str_replace('{#'.$key.'#}',$val,$weixin_title);
                 $weibo_content = str_replace('{#'.$key.'#}',$val,$weibo_content);
                 $copylink_content = str_replace('{#'.$key.'#}',$val,$copylink_content);
             }

             $product_days = $this->get_dates($model['id'],$product);
             $days_str = array();
             foreach($product_days as $day)
             {
                 $days_str[] = date('m-d',$day);
             }
             //预估佣金
             $fenxiao_profit = $this->get_prospect_fenxiao_price($model['id'],$product);
             $this->assign('fenxiao_profit',$fenxiao_profit);
             $this->assign('weixin_title',$weixin_title);
             $this->assign('product_title',$product['title']);
             $this->assign('product_price',$price);
             $this->assign('product_sellpoint',$product['sellpoint']);
             $this->assign('product_litpic',$product['litpic']);
             $this->assign('product_piclist',$product_piclist);
             $this->assign('product_days',$product_days);
             $this->assign('product_days_str',implode(', ',$days_str));
             $this->assign('days_str',$days_str);

             $this->assign('weibo_content',$weibo_content);
             $this->assign('copylink_content',$copylink_content);
         }

         $member_info = Model_Member_Login::check_login_info();
         $member_info = Model_Member::get_member_byid($member_info['mid']);
         //外网头像地址
         if(stristr($member_info['litpic'],'http') || stristr($member_info['litpic'],'https') ||stristr($member_info['litpic'],'qlogo.cn')){
             $face_pic = Model_Fenxiao::dowload_picture($member_info['litpic']);
             $member_info['litpic'] = substr($face_pic,stripos($face_pic,'/uploads'),strlen($face_pic));
             unset($face_pic);
         }

         //$code_pic = Model_Fenxiao::download_code($url);
         $fenxiao_pic_templet = Model_Fenxiao_Config::get_val('cfg_fenxiao_pic_templet');
         $product_code_pic = DB::select()->from('fenxiao_product')->where('typeid','=',$model['id'])->and_where('productid','=',$product['id'])->execute()->get('litpic');
         if(strpos($product_code_pic,'http://')!==false || strpos($product_code_pic,'https://')!==false)
         {
             $down_pic = Model_Fenxiao::dowload_picture($product_code_pic);
             $product_code_pic = $down_pic;
         }
         $imgpath = self::imgpath($member_info,$match,$url);
         $this->assign('imgpath',$imgpath);
         $this->assign('member',$member_info);
         $this->assign('fenxiao_pic_parts_arr',$fenxiao_pic_parts_arr);
         $this->assign('fenxiao_ways',$fenxiao_ways);
         $this->assign('fenxiao_pic_introduce',$fenxiao_pic_introduce);
         $this->assign('fenxiao_pic_introduce_tpl1',$fenxiao_pic_introduce_tpl1);
         $this->assign('fenxiao_pic_templet',$fenxiao_pic_templet);
         $this->assign('logo',$logo);
         $this->assign('url',$url);
         $this->assign('product_code_pic',$product_code_pic);
         //  $this->assign('code_pic',$code_pic);
         $tpl = $isnew==1?'share_new':'share_old';
         $this->assign('fenxiao_pic_templet',$fenxiao_pic_templet);
         $this->display('../mobile/fenxiao/jieshao/'.$tpl);

     }

     /**
      * @function 合成分销图片
      * @param $member_info
      * @param $match
      * @param $url
      * @return bool|mixed
      */
     public function imgpath($member_info,$match,$url)
     {
         $temple_type = Model_Fenxiao_Config::get_val('cfg_fenxiao_pic_templet');

         $fxurl = $match[0];
         $aid = $match[4];
         $pinyin = $match[3];
         $_model = DB::select('id')->from('model')->where('pinyin','=',$pinyin)
             ->execute()
             ->current();
         if(!$aid || !$pinyin){
             return false;
         }
         $list=ORM::factory('fenxiao_config')->get_all();
         $info=array();
         foreach($list as $v){
             $info[$v['varname']]=$v['value'];
         }
         $pic_parts_arr = explode(',',$info['cfg_fenxiao_pic_parts']);
         if($_model['id']>199){
             $product_info = DB::select()
                 ->from('model_archive')
                 ->where('typeid','=',$_model['id'])
                 ->where('aid','=',$aid)
                 ->execute()
                 ->as_array();
         }else{
             $model = DB::select()->from('model')->where('correct','=',$pinyin)->or_where('pinyin','=',$pinyin)->execute()->current();
             $product_id = DB::select('id')->from($model['pinyin'])->where("aid={$aid}")->execute()->get('id');
             $product_info = St_Product::get_product_info($model['id'], $product_id);
         }


         /*判断目录是否存在，不存在就创建*/
         $lujing = BASEPATH.'/uploads/uniapp/productCode/h5/'.date('Y',time());
         if(!is_dir($lujing)){
             mkdir(iconv("UTF-8", "GBK", $lujing),0777,true);
         }
         $lujing = BASEPATH.'/uploads/uniapp/distribution/product/h5/';
         if(!is_dir($lujing)){
             mkdir(iconv("UTF-8", "GBK", $lujing),0777,true);
         }

         /* 获取产品分销二维码 */
         $codeRes = Model_Fenxiao_Shareposter::get_product_code($fxurl,$product_info['id'],$member_info['mid'],'h5',$url);
         if(!$codeRes['status'])
         {
             return false;
         }

         $codeImg = $codeRes['path'];
         
         if($member_info['litpic'][0]!='/') $member_info['litpic'] = DS.$member_info['litpic'];
         $faceImg = $member_info['litpic'];
         if(stripos($member_info['litpic'],'nopic')&&!stripos($member_info['litpic'],'phone')){
             $faceImg = '/phone'.$faceImg;
         }else{
             $faceImg = substr($member_info['litpic'],stripos($member_info['litpic'],'/uploads'),strlen($member_info['litpic']));
         }

         // 高级海报
         $litpic = DB::select("litpic")->from("fenxiao_product")
             ->where("productid", "=", $product_id)
             ->and_where("typeid", "=", $model['id'])
             ->execute()->get('litpic');
         if(!empty($litpic)) {
             // 高级海报
             if(strstr($litpic,'http')){
                 $litpic = Model_Fenxiao::dowload_picture($litpic);
             }
             $filename = md5('h5'.$member_info['mid'].$litpic.$product_id.$model['id']).'.jpg';
             $path = "/uploads/uniapp/distribution/product/h5/".$filename;

             // 检查文件是否存在
             $savePath = BASEPATH.$path;

             $params = array(
                 'bg' => array(
                     'path'=> BASEPATH. $litpic
                 ),
                 'codeImg'=> array(
                     'path'=> BASEPATH.$codeImg,
                 )
             );
             //生成高级海报
             Model_Fenxiao_Shareposter::best_poster($savePath,$params);
             return str_replace(BASEPATH,'',$savePath);
         }

         /* 标准海报 */
         if($temple_type==0){
             $params = array();
             $usedate = Model_Fenxiao_Shareposter::get_product_price_date($product_info['id'],$model['id']);
             $list = Product::pic_list($product_info['piclist']);
             $pic_arr = array();
             $count = count($list);
             foreach ($list as $key=>$vel)
             {
                 if(strstr($vel[0],'http')){
                     $http_img = Model_Fenxiao::dowload_picture($vel[0]);
                     if($http_img){
                         array_push($pic_arr,BASEPATH.$http_img);
                     }

                 }else{
                     array_push($pic_arr,BASEPATH.$vel[0]);
                 }
             }

             if(in_array('logo',$pic_parts_arr)){
				 //$logo = $GLOBALS['cfg_m_logo'];
                 $logo =Model_Fenxiao_Config::get_val('cfg_fenxiao_df_fx_shop_logo');
				 if($logo && strstr($logo,'http')){
					$logo = Model_Fenxiao::dowload_picture($logo);
				 }
                 !empty($GLOBALS['cfg_m_logo'])?$params['logo']['path']=BASEPATH.$logo:false;
             }
             !empty($product_info['title'])?$params['title']['text']=$product_info['title']:false;
             if(in_array('sellpoint',$pic_parts_arr)){
                 !empty($product_info['sellpoint'])?$params['sealPoint']['text']=$product_info['sellpoint']:false;
                 !empty($product_info['sellpoint'])?$params['sealPoint']['line']=5:false;
             }
             if(in_array('date',$pic_parts_arr)){
                 !empty($usedate)?$params['useDate']['text']=$usedate:false;
             }
             if(in_array('litpic',$pic_parts_arr)){
                 if($product_info['litpic']){
                     if(strstr($product_info['litpic'],'http')){
                         $http_img = Model_Fenxiao::dowload_picture($product_info['litpic']);
                         $params['litpic']['path'] = $http_img?BASEPATH.$http_img:'';
                     }else{
                         $params['litpic']['path'] = BASEPATH.$product_info['litpic'];
                     }
                 }
             }
             if(in_array('piclist',$pic_parts_arr)){
                 $count>0?$params['piclist'] = array('num'=>$count,'path'=>$pic_arr):false;
             }
             if(in_array('introduce',$pic_parts_arr)){
                 !empty($info['cfg_fenxiao_pic_introduce'])?$params['tips']['text']=strip_tags($info['cfg_fenxiao_pic_introduce']):false;
             }


             $params['distribution']=array(
                 'codeImg'=>BASEPATH.$codeImg,
             );
             if(in_array('fx',$pic_parts_arr)){
                 //分销商数据
                 if(!empty($member_info['email'])){
                     $accout = $member_info['email'];
                 }
                 if(!empty($member_info['mobile'])){
                     $accout = $member_info['mobile'];
                 }
                 $username = $member_info['truename'] ? $member_info['truename'] : $member_info['nickname'];
                 $params['distribution']=array(
                     'username'=>$username,
                     'face'=>BASEPATH.$faceImg,
                     'account'=>$accout
                 );
             }
             !empty($product_info['price'])?$params['price']['text']=$product_info['price']:false;

             $filename = md5('h5'.$member_info['mid'].$product_info['litpic'].$product_id.$model['id']).'.jpg';
             $path = "/uploads/uniapp/distribution/product/h5/".$filename;
             $savePath = BASEPATH.$path;
             //var_dump($params);exit;
             Model_Fenxiao_Shareposter::standard_mould1($savePath,$params);

             $imgpath =  str_replace(BASEPATH,'',$savePath);
         }else{
             /*模板海报*/
			 if(strstr($product_info['litpic'],'http')){
                 $product_info['litpic'] = Model_Fenxiao::dowload_picture($product_info['litpic']);
             }
             $params['banner']=array('path'=>BASEPATH.$product_info['litpic']);
             $params['face']=array('path'=>BASEPATH.$faceImg);
             $params['codeImg']=array('path'=>BASEPATH.$codeImg);
             $params['price']=array('text'=>$product_info['price']);
             $params['title']=array('text'=>$product_info['title']);
             $params['sellpoint']=array('text'=>$product_info['sellpoint']);
             // 使用时间
             $str = Model_Fenxiao_Shareposter::get_product_price_date($product_info['id'],$model['id']);
             $params['date']     =  array('text'=>$str);
             // 用户信息
             $username = $member_info['truename'] ? $member_info['truename'] : $member_info['nickname'];
             $params['username'] = array('text'=>$username);
             if(!empty($member_info['email']))
             {
                 $accout=$member_info['email'];
             }
             if(!empty($member_info['mobile']))
             {
                 $accout=$member_info['mobile'];
             }
             $params['account']=array('text'=>$accout);
             // 保存位置
             $filename = md5('h5'.$member_info['mid'].$product_info['litpic'].$product_id.$model['id']).'.jpg';
             $path = "/uploads/uniapp/distribution/product/h5/".$filename;
             $savePath = BASEPATH.$path;
             Model_Fenxiao_Shareposter::standard_mould2($savePath,$params);

             $imgpath = str_replace(BASEPATH,'',$savePath);
         }

         return $imgpath;
     }

     //获取预估分销价格
     private function get_prospect_fenxiao_price($typeid,$product)
     {
         $member_info = Model_Member_Login::check_login_info();
         $fenxiao = DB::select()->from('fenxiao')->where('memberid','=',$member_info['mid'])->execute()->current();
         $commission_type=Model_Fenxiao_Config::get_val('cfg_fenxiao_commission_type_'.$typeid,$fenxiao['fxgroupid']);
         $min_price = $this->get_price($typeid,$product['id']);

         $product['price'] = empty($product['price'])?0:$product['price'];
         $min_price = is_array($min_price)?$min_price['price']:$min_price;
         $min_price = empty($min_price)?0:$min_price;
         $product['price'] = !empty($min_price)?$min_price:$product['price'];

         if($commission_type==1)
         {
             $commission_rate = Model_Fenxiao::get_commission_rate($typeid,$product['id'],$fenxiao['fxgroupid']);
             $profit =number_format($product['price']*$commission_rate[0],2);
         }
         else if($commission_type==2)
         {
             $commission_rate = Model_Fenxiao::get_commission_rate_platform($typeid,$product['id'],$fenxiao['fxgroupid']);

             $temp_order = array('typeid' => $typeid, 'productautoid' => $product['id'], 'totalprice' => $product['price'], 'dingnum' => 1,'channel_id'=>1);
             $platform_price = Model_Member_Order_Compute::caculate_platform_commission($temp_order);

             $profit = number_format($platform_price*$commission_rate[0],2);
         }
         else
         {
             $commission_cash = Model_Fenxiao::get_commission_cash_line($typeid,$product['id'],$fenxiao['fxgroupid']);
             $profit =number_format($commission_cash[0]['adult'],2);
         }
         return $profit;
     }
     public function action_ajax_get_weixininfo()
     {
         $url=$_POST['url'];
         $cfg_wx_appid=Model_Fenxiao_Config::get_val('cfg_fenxiao_wx_appid');
         $cfg_wx_appsecret=Model_Fenxiao_Config::get_val('cfg_fenxiao_wx_appsecret');

         $default_litpic = Model_Fenxiao_Config::get_val('cfg_fenxiao_weixin_other_litpic');
         $default_title = Model_Fenxiao_Config::get_val('cfg_fenxiao_weixin_other_title');
         $default_description = Model_Fenxiao_Config::get_val('cfg_fenxiao_weixin_other_description');

         $default_litpic = !empty($default_litpic)? Common::img($default_litpic):'';
         $result=file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$cfg_wx_appid}&secret={$cfg_wx_appsecret}");

         try {
             //throw new Exception(var_export($result,true));
             if(!$result)
                 throw new Exception("未能获取微信token");
             $result = json_decode($result, true);
             $accessToken = $result['access_token'];
             if(!$accessToken)
                 throw new Exception('未能获取微信token');
             $ticketResult = file_get_contents("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$accessToken}&type=jsapi");
             $ticketResult = json_decode($ticketResult,true);
             $ticket=$ticketResult['ticket'];
             if(!$ticket)
                 throw new Exception('未能获取微信ticket');
             $noncestr = $this->get_wx_noncestr();
             $timestamp = time();
             $queryArr=array('jsapi_ticket'=>$ticket,'noncestr'=>$noncestr,'timestamp'=>$timestamp,'url'=>$url);
             $queryStr='';
             foreach($queryArr as $k=>$v)
             {
                 $queryStr.=$k.'='.$v.'&';
             }
             $queryStr=substr($queryStr,0,-1);
             $signature=sha1($queryStr);
             $data=array('appid'=>$cfg_wx_appid,'ticket'=>$ticket,'noncestr'=>$noncestr,'timestamp'=>$timestamp,'signature'=>$signature,'default_title'=>$default_title,'default_description'=>$default_description,'default_litpic'=>$default_litpic);
             echo json_encode(array('status'=>true,'msg'=>'获取成功','data'=>$data));

         }catch (Exception $excep)
         {
             echo json_encode(array('status'=>false,'msg'=>$excep->getMessage()));
         }

     }

     private function get_wx_noncestr()
     {
         $charStr='abcdefghijklmnopqrstuvwxyz123456789';
         $len=strlen($charStr)-1;
         $str='';
         for($i=0;$i<10;$i++)
         {
             $index=mt_rand(0,$len);
             $str.=$charStr[$index];
         }
         return $str;
     }

     private  function get_dates($typeid,$product)
     {
         $days_arr = array();
         if($typeid==1)
         {
             $today_time = strtotime(date('Y-m-d'));
             if ($product['islinebefore'] > 0 && $product['linebefore'] > 0)
             {
                 $today_time = strtotime("+{$product['linebefore']} days", $today_time);
             }
             $sql = 'SELECT day FROM sline_line_suit_price WHERE `lineid`=' . $product['id'] . ' and  `day`>=' . $today_time . ' and (`number` >0 or `number`=-1) group by day order by day limit 5';
             $days = DB::query(Database::SELECT,$sql)->execute()->as_array();
             foreach($days as $row)
             {
                 $days_arr[] = $row['day'];
             }
         }
         return empty($days_arr)?null:$days_arr;
     }
     public function action_test()
     {
        echo  Model_Fenxiao::download_code('http://www.baidu.com');
     }

     //获取某个产品的最低价
     private function get_price($typeid,$productid)
     {
         $model_info = DB::select()->from('model')->where('id','=',$typeid)->execute()->current();

         $maintable = $model_info['maintable'];
         $letter_arr = explode('_',$maintable);
         foreach($letter_arr as &$letter)
         {
             $letter = ucfirst($letter);
         }
         $class_name='Model_'.implode('_',$letter_arr);
         $price = 0;
         if(class_exists($class_name)&& method_exists($class_name,'get_minprice') )
         {
             $price = call_user_func(array($class_name, 'get_minprice'),$productid);
         }
         return $price;
     }

 }

